/**
 * Captain
 * © 2017 Captain copyright，All rights reserved.
 * http://www.sccaptain.com.cn
 * <p>
 * JAVA : 8
 * 文  件  名: CustomWebAppRootListener.java
 * 创  建  人: liujian (liu.jian@sccaptain.com.cn)
 * 创建时间: 2017/10/19 15:48
 * 版         本: 1.0.0
 * 备         注:
 * 修订历史:
 */

package com.material.c2c.web.sys.listener;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.util.WebAppRootListener;
import org.springframework.web.util.WebUtils;

import com.material.c2c.util.SystemUtil;

/**
 * WebAppRootListener扩展
 *
 * @since 1.0
 * @version 1.0
 * @author liujian (liu.jian@sccaptain.com.cn)
 */
public class CustomWebAppRootListener extends WebAppRootListener {

  private final Logger logger = LoggerFactory.getLogger(getClass());

  /**
   * 电子政务系统id
   */
  public static final String DZZWXT_ID = "25acdf37-da4e-11e7-ba0e-305a3a7f8a9b";

  /**
   * 在WebAppRootListener设置System Property之后同时设置SystemUtil中的RootPath属性
   * @param event
   */
  @Override
  public void contextInitialized(ServletContextEvent event) {
    super.contextInitialized(event);
    WebApplicationContext applicationContext = ContextLoader.getCurrentWebApplicationContext();
    ServletContext servletContext = applicationContext.getServletContext();

    String rootKey = servletContext.getInitParameter(WebUtils.WEB_APP_ROOT_KEY_PARAM);
    SystemUtil.setRootPath(System.getProperty(rootKey));

    //读取系统配置文件
    String resourcePath = "/WEB-INF/classes/application.properties", propertyName = "attachment.path";
    InputStream inputStream = servletContext.getResourceAsStream(resourcePath);
    Properties properties = new Properties();
    try {
      properties.load(new InputStreamReader(inputStream, SystemUtil.ENCODE));
    } catch (Exception e) {
      logger.error("系统配置文件读取失败", e);
    }

    //读取附件存放目录
    try {
      String attachmentPath = properties.getProperty(propertyName);
      if (StringUtils.hasText(attachmentPath)) {
        File file = new File(attachmentPath);
        if (!file.exists()) {
          logger.warn("附件存放路径\"{}\"不存在，系统将自动创建。", attachmentPath);
          file.mkdirs();
        }
        if (file.canWrite()) {
          SystemUtil.setAttachmentPath(attachmentPath);
        }
      }
    } catch (Exception e) {
      logger.error("附件存放路径配置读取失败", e);
    } finally {
      if (!StringUtils.hasText(SystemUtil.getAttachmentPath())) {
        logger.debug("未找到附件存放路径配置，默认使用系统当前目录。");
        SystemUtil.setAttachmentPath(SystemUtil.getRootPath() + SystemUtil.SEPARATOR + SystemUtil.ATTACHMENT_FOLDER);
      }
    }

    //读取授权信息
    String licenseName = "license.key";
    String licenseKey = System.getProperty(licenseName);
    if (!StringUtils.hasText(licenseKey)) {
      licenseKey = properties.getProperty(licenseName);
    }
    boolean invalid = false;
//    try {
//      if (StringUtils.hasText(licenseKey)) {
//        AuthCodeGenerate.AuthorityInfo authorityInfo = AuthCodeGenerate.ParseAuthorityCode(licenseKey);
//        List<String> ids = getAppIds(servletContext);
//        if (ids.stream().noneMatch(id -> id.equals(authorityInfo.getAppId()))) {
//          invalid = true;
//          logger.error("授权码不能用于本产品（本机机器码：{}）。", AuthCodeGenerate.getComputerId());
//        } else if (authorityInfo.getEndTime() != null && new Date().after(authorityInfo.getEndTime())) {
//          invalid = true;
//          logger.error("授权码已过期（本机机器码：{}）。", AuthCodeGenerate.getComputerId());
//        }
//      } else {
//        logger.error("产品还未授权（本机机器码：{}）。", AuthCodeGenerate.getComputerId());
//        invalid = true;
//      }
//    } catch (Exception e) {
//      invalid = true;
//      logger.error("授权码无效（本机机器码：{}）。", AuthCodeGenerate.getComputerId());
//    } finally {
//      if (invalid) System.exit(-1);
//    }
  }

  /**
   * 获取appid列表
   * @param servletContext
   * @return
   * @throws IOException
   */
  public List<String> getAppIds(ServletContext servletContext) {
    List<String> ids = new ArrayList<>();
    ids.add(DZZWXT_ID);
    try {
      String appidKey = "appid";
      InputStream inputStream = servletContext.getResourceAsStream("/META-INF/MANIFEST.MF");
      Manifest manifest = new Manifest(inputStream);
      Attributes attributes = manifest.getMainAttributes();
      String id = attributes.getValue(appidKey);
      if (StringUtils.hasText(id)) {
        ids.add(id);
      }
    } catch (Exception e) {
      logger.warn("读取appid失败", e);
    }
    return ids;
  }

}
